package columnEditors;

import java.awt.Color;
import java.awt.Component;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;



public class JTableRenderer extends DefaultTableCellRenderer{

	private static final long serialVersionUID = 1544226259334346744L;

	private ArrayList<CellData> editedCells = new ArrayList<CellData>();
	private ArrayList<CellData> commitedCells = new ArrayList<CellData>();
	
	private static final Color EDITED_DATA = Color.GRAY;
	private static final Color NORMAL_COLOR = Color.WHITE;
	private static final Color COMMITED_COLOR = Color.YELLOW;
	
	public JTableRenderer() {
		super();
	}
	
	@Override
	public Component getTableCellRendererComponent(
			JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
		
		Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
		
		CellData cellData = new CellData(row, column);
		if (editedCells.contains(cellData)) {
			comp.setBackground(EDITED_DATA);
		}
		else if(commitedCells.contains(cellData)) {
			comp.setBackground(COMMITED_COLOR);
		}
		else 
			comp.setBackground(NORMAL_COLOR);
		
		return comp;
	}
	
	public void addEditedCell(int row, int column) {
		CellData cellData = new CellData(row, column);
		
		this.commitedCells.remove(cellData);
		this.editedCells.add(cellData);
		
	}
	
	public void addCommitedCells(int row, int column) {
		CellData cellData = new CellData(row, column);
		
		this.editedCells.remove(cellData);
		this.commitedCells.add(cellData);
	}
	
	public void clearEditedCells() {
		this.editedCells.clear();
	}
	
	public void clearCommitedCells() {
		this.commitedCells.clear();
	}
	
	public void addCommitedRow(int row) {
		CellData cellData = null;
		
		Iterator<CellData> ith = editedCells.iterator();
		
		while (ith.hasNext()) {
			cellData = ith.next();
			if (cellData.getRow() == row) {
				ith.remove();
				this.commitedCells.add(cellData);
			}
		}
	}
	
	class CellData {
		
		private int row;
		private int column;
		
		public CellData(int row, int column) {
			this.setCellPos(row, column);
		}
		
		public boolean equals(Object o) {
			CellData data = (CellData)o;
			
			if (data.getRow() == this.getRow() &&
					data.getColumn() == this.getColumn())
				return true;
			return false;
		}
		
		public void setCellPos(int row, int column) {
			this.setRow(row);
			this.setColumn(column);
		}
		
		public void setRow(int row) {
			this.row = row;
		}
		
		public void setColumn(int column) {
			this.column = column;
		}
		
		public int getRow() {
			return this.row;
		}
		
		public int getColumn() {
			return this.column;
		}
	}


	
}
